<template>
  <view class="flex flex-col w-[750rpx] min-h-screen bg-gray-100">
    <!-- 顶部导航栏 -->
    <view class="flex items-center h-[100rpx] bg-green-500 px-[24rpx] text-white">
      <view class="w-[40rpx] h-[40rpx] mr-[24rpx]" @tap="goBack">
        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="w-full h-full">
          <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round"
            stroke-linejoin="round" />
        </svg>
      </view>
      <view class="flex-1 text-center text-[32rpx] font-medium mr-[64rpx]">Anfine代购大药房</view>
    </view>

    <!-- 一级分类 -->
    <view class="flex bg-white px-[24rpx] border-b border-b-1 border-solid border-gray-200 overflow-x-auto">
      <view v-for="category in cateList1" :key="category.itemValue"
        class="py-[24rpx] px-[32rpx] text-[24rpx] text-gray-600 whitespace-nowrap min-w-[160rpx] text-center transition-all duration-300"
        :class="{
          'text-green-500 border-b-2 border-green-500': act1 === category.itemValue
        }" @tap="selectCategory(category.itemValue)">
        {{ category.itemText }}
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="flex flex-1 overflow-hidden">
      <!-- 左侧二级分类 -->
      <view class="w-[210rpx] bg-white border-r border-gray-200 p-1 overflow-y-auto">
        <view v-for="subCategory in cateList2" :key="subCategory.id"
          class="py-[10rpx] px-[12rpx] text-[24rpx] text-gray-800 border-b border-gray-100 transition-all duration-300"
          :class="{
            'bg-green-500 text-white rounded-[10rpx] mx-[6rpx] my-[4rpx] border-none': act2 === subCategory.id,
            'hover:bg-gray-50': act2 !== subCategory.id
          }" @tap="selectSubCategory(subCategory.id)">
          {{ subCategory.typeName }}
        </view>
      </view>

      <!-- 右侧内容区域 -->
      <view class="flex-1 p-[20rpx] overflow-y-auto">
        <!-- 健康服务标题 -->
        <view class="mb-[30rpx] w-full flex overflow-x-auto">
          <!-- 三级分类 -->
          <nut-button class="text-[32rpx]" v-for="sonCategory in cateList3"
            :type="act3 === sonCategory.id ? 'success' : 'default'" plain :key="sonCategory.id" size="small"
            @tap="selectSonCategory(sonCategory.id)">{{ sonCategory.typeName }}</nut-button>
        </view>

        <!-- 商品列表 -->
        <view class="space-y-[20rpx]">
          <view v-for="product in currentProducts" :key="product.id"
            class="bg-white relative rounded-[8rpx] p-[12rpx] transition-all duration-300 shadow-sm flex items-center gap-[24rpx]"
            hover-class="transform -translate-y-[4rpx] shadow-md">
            <view class="w-[120rpx] h-[120rpx] rounded-[12rpx] overflow-hidden flex-shrink-0"
              @tap="selectProduct(product)">
              <image :src="useImage(product.pic)" class="w-full h-full object-cover bg-gray-200" />
            </view>
            <view class="flex-1" @tap="selectProduct(product)">
              <view class="text-[24rpx] font-semibold text-green-500 mb-[6rpx]">{{ product.goodsType_dictText }}</view>
              <view class="text-[20rpx] text-gray-600 mb-[18rpx] leading-snug">{{ product.typeName }}</view>
              <view class="text-[28rpx] font-semibold text-red-500">¥ {{ product.standPrice }}</view>
            </view>
            <nut-button class="!absolute bottom-[10rpx] right-[10rpx] scale-80" shape="square" type="success" plain
              size="mini" @tap="addToCart(product)">添加购物车</nut-button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
// import { ref, computed } from 'vue'
import { ref, watch, computed, onMounted } from 'vue';
import { useImage } from '@/hooks';
import { useRouterPush } from '@/composables';
import { useNurseGoods, useDict } from '@/service';
import { useCartStore, type CartItem } from '@/store/modules/cart';
// import { useNurseOrders, useDict } from '@/service';
import Taro, { hideLoading, showLoading, showToast, usePullDownRefresh, stopPullDownRefresh } from '@tarojs/taro';

import good from './good.vue';
import { useTempShopStore } from '@/store/modules/shop/temp';
const tempShopStore = useTempShopStore();

interface DictItem {
  itemValue: string | number;
  itemText: string;
}
interface CategoryNode {
  id: string | number;
  pid: string | number;
  typeName: string;
  children: CategoryNode[];
  // product properties
  pic?: string;
  goodsType_dictText?: string;
  price?: number;
}
// import { categories as categoriesData, products as productsData } from './shop'
// import { useGetAuthInfo, useGlobal, useImage } from '@/hooks';
const { getDict } = useDict();
const { getShopGoodsList, loadTreeChildrenNew, loadShopTreeChildren } = useNurseGoods();
const cartStore = useCartStore();
// 药品分类数据（3级结构）
const cateList1 = ref<DictItem[]>([]);

// 当前选中的分类
const act1 = ref<number | string | null>(); // 默认选中中药饮片
const act2 = ref<number | string | null>(); // 默认选中消化道分类
const act3 = ref<number | string | null>(); // 默认选中消化道分类

// 计算当前二级分类
const cateList2 = ref<CategoryNode[]>([]);
const cateList3 = ref<CategoryNode[]>([]);
// const cateList2 = computed(() => {
//   const category = cateList1.value.find(cat => cat.id === act1.value)
//   return category ? category.children : []
// })

// 计算当前商品列表
const currentProducts = ref<CategoryNode[]>([]);

// 方法
const goBack = () => {
  // 返回上一页
  Taro.navigateBack();
};
const addToCart = (product: CategoryNode) => {
  const obj: any = { ...product }
  obj.price = obj.standPrice || 0
  if (typeof product.price === 'number') {
    if (tempShopStore.showAdd) {
      tempShopStore.addGoods(obj)
      Taro.showToast({
        title: '添加成功',
        icon: 'none'
      });
    } else {
      cartStore.addToCart(obj as Omit<CartItem, 'quantity'>);
    }
  } else {
    Taro.showToast({
      title: '该商品无法添加',
      icon: 'none'
    });
  }
}
//选择一级分类
const selectCategory = (categoryId: string | number) => {
  act1.value = categoryId;
};

//选择二级分类
const selectSubCategory = (subCategoryId: string | number) => {
  act2.value = subCategoryId;
};

const selectSonCategory = (sonCategoryId: string | number) => {
  act3.value = sonCategoryId;
};

const selectProduct = (product: CategoryNode) => {
  // 选择商品

  // 将商品信息保存到本地缓存
  try {
    Taro.setStorageSync('selectedProduct', product)
    // 商品信息已保存到缓存

    // 跳转到商品详情页
    Taro.navigateTo({
      url: '/pages/product-detail/index'
    })
  } catch (error) {
    // 保存商品信息失败
    Taro.showToast({
      title: '保存商品信息失败',
      icon: 'none'
    })
  }
}
onMounted(async () => {
  const res = await getDict("shop_type");//nurse_type shop_type
  // 大药房类型 res
  cateList1.value = res || [];
  act1.value = cateList1.value[0].itemValue;
})

function buildTree(records: any[]): CategoryNode[] {
  const map: Record<string | number, CategoryNode> = {};
  const roots: CategoryNode[] = [];

  // First create a map of all items by their id
  records.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });

  // Then build the tree by assigning children to their parents
  records.forEach(item => {
    const parent = map[item.pid];
    if (parent) {
      parent.children.push(map[item.id]);
    } else if (item.pid === '0') {
      roots.push(map[item.id]);
    }
  });

  return roots;
}

const getCate2Data = async () => {
  // modelValue.value
  const id = act1.value;
  const { success } = await loadShopTreeChildren({ goodsType: id, pid: '' });
  // success
  const tree = buildTree(success.records);
  // tree
  cateList2.value = tree;
  if (cateList2.value.length > 0) {
    act2.value = cateList2.value[0].id;
  } else {
    act2.value = null;
    cateList3.value = [];
    currentProducts.value = [];
  }
};
watch(
  () => act1.value,
  () => {
    getCate2Data();
  },
  { immediate: true }
);

const getCate3Data = async () => {
  const id = act2.value;
  if (!id) {
    cateList3.value = [];
    currentProducts.value = [];
    act3.value = null;
    return;
  }
  const selectedCate2 = cateList2.value.find(item => item.id === id);
  if (selectedCate2 && selectedCate2.children) {
    cateList3.value = selectedCate2.children;
    if (cateList3.value.length > 0) {
      act3.value = cateList3.value[0].id;
    } else {
      act3.value = null;
      currentProducts.value = [];
    }
  } else {
    cateList3.value = [];
    currentProducts.value = [];
    act3.value = null;
  }
};

const getCurrentProductsData = async () => {
  const id = act3.value;
  if (!id) {
    currentProducts.value = [];
    return;
  }
  const selectedCate3 = cateList3.value.find(item => item.id === id);

  if (selectedCate3 && selectedCate3.children) {
    currentProducts.value = selectedCate3.children;
  } else {
    currentProducts.value = [];
  }
};
watch(
  () => act2.value,
  () => {
    getCate3Data();
  }
);
watch(
  () => act3.value,
  () => {
    getCurrentProductsData();
  }
);

// 暴露方法给父组件，供机构切换时调用
defineExpose({
  getCate2Data
});
</script>

<style>
/* 全局样式可以放在这里 */
page {
  background-color: #f5f5f5;
}
</style>